import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/auth',
    component: () => import('@/layouts/AuthLayout.vue'),
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/auth/LoginView.vue')
      },
      {
        path: 'register',
        name: 'Register',
        component: () => import('@/views/auth/RegisterView.vue')
      }
    ]
  },
  {
    path: '/chat',
    component: () => import('@/layouts/ChatLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Chat',
        component: () => import('@/views/chat/ChatView.vue')
      },
      {
        path: ':id',
        name: 'ChatDetail',
        component: () => import('@/views/chat/ChatView.vue')
      }
    ]
  },
  {
    path: '/',
    redirect: (to) => {
      const authStore = useAuthStore()
      return authStore.token ? '/chat' : '/auth/login'
    }
  },
  // 捕获所有未匹配的路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.meta.requiresAuth && !authStore.token) {
    next('/auth/login')
  } else if (authStore.token && to.path.startsWith('/auth')) {
    next('/chat')
  } else {
    next()
  }
})

export default router 